package com.lunevich.json.activity;

import java.util.List;

import com.lunevich.json.R;
import com.lunevich.json.adapter.ApplicationAdapter;
import com.lunevich.json.items.ApplicationItem;
import com.lunevich.json.tasks.XMLAsyncTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ListView;
import android.widget.ProgressBar;

public class XMLActivity extends Activity {

	private String url = "https://dl.dropbox.com/u/16403954/apps.xml";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.list);

		/* Create a new TextView to display the parsing result later. */
		final ListView list = (ListView) findViewById(R.id.listView);
        final ProgressBar loading = (ProgressBar) findViewById(R.id.preload);

		new XMLAsyncTask<ApplicationItem>(this) {

			@Override
			public void onLoadSuccess(List<ApplicationItem> contactList) {
				ApplicationAdapter jsonAdapter = new ApplicationAdapter(XMLActivity.this,  contactList);
				list.setAdapter(jsonAdapter);
				loading.setVisibility(View.INVISIBLE);
			}

			@Override
			public void onLoadError(Exception exception) {
				loading.setVisibility(View.INVISIBLE);
				showErrorDialog(exception);
			}
		}.execute(url);
	}
	
	private void showErrorDialog(Exception exception) {
    	AlertDialog.Builder builder = new AlertDialog.Builder(XMLActivity.this);
		builder.setMessage(exception.getMessage() + ".   EXIT ? ")
		       .setCancelable(false)
		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   XMLActivity.this.finish();
		           }
		       })
		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		AlertDialog alert = builder.create();
		alert.show();
    }
}